package com.fenfen.novel.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.fenfen.novel.R;
import com.fenfen.novel.db.NovelReadRecord;
import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.DescIntComparator;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NovelReadRecordAdapter extends RecyclerView.Adapter<NovelReadRecordAdapter.NovelRecordViewHolder> {

  private List<NovelReadRecord> mData = new ArrayList<>();
  private Context mContext;

  private static int VIEW_TYPE_NOVEL = 1;
  private static int VIEW_TYPE_LOAD = 2;

  private boolean hasLoadingMore;

  private NovelRecordItemClickListener mItemClickListener;

  private int colorAccent;

  public NovelReadRecordAdapter(Context context) {
    this.mContext = context;
    colorAccent = CommonUtil.resolveColor(mContext, R.attr.colorAccent);
  }

  public void setNovalItemClickListener(NovelRecordItemClickListener mItemClickListener) {
    this.mItemClickListener = mItemClickListener;
  }

  public void setHasLoadingMore(boolean hasLoadingMore) {
    this.hasLoadingMore = hasLoadingMore;
    notifyDataSetChanged();
  }

  public boolean isHasLoadingMore() {
    return hasLoadingMore;
  }

  public void clearData() {
    if (mData != null && mData.size() > 0) {
      mData.clear();
      notifyDataSetChanged();
    }
  }

  public void setData(List<NovelReadRecord> list) {
    mData.clear();
    if (list != null && list.size() > 0) {
      mData.addAll(list);
    }
    notifyDataSetChanged();
  }

  public void addData(List<NovelReadRecord> list) {
    if (list != null && list.size() > 0) {
      int positionStart = mData.size();
      mData.addAll(list);
//      notifyDataSetChanged();
      notifyItemRangeInserted(positionStart, list.size());
    }
  }

  @Override
  public NovelRecordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_read_log_item, parent, false);
    NovelRecordViewHolder vh = new NovelRecordViewHolder(view);
    return vh;
  }

  @Override
  public void onBindViewHolder(NovelRecordViewHolder holder, int position) {
    if (hasLoadingMore && position == mData.size()) {
      //done nothing
    } else {
      NovelReadRecord novel = mData.get(position);
      holder.novelName.setText(novel.getNovelName());
      int progress = 0;
      if (novel.getChapterCount() != 0) {
        progress = (int) (novel.getChapterOrder() * 100.0 / novel.getChapterCount());
      }
      holder.novelProgress.setText(String.format(mContext.getString(R.string.novel_progress), progress));
      CommonUtil.filterDrawableColor(mContext, holder.novelDownStatus.getBackground(), R.attr.colorAccent);
      String coverlUrl = novel.getNovelCover();
      if (mContext != null && !TextUtils.isEmpty(coverlUrl)) {
        coverlUrl = CommonUtil.PRE_COVER_URL + coverlUrl;
        Picasso.with(mContext).load(coverlUrl).placeholder(R.drawable.nocover).into(holder.novelCover);
      }
      if (novel.getDownStatus().equals(CommonUtil.DOWN_STATUS.SUCCESS) && CommonUtil.isNovelFileExist(mContext, novel.getNovelId())) {
        holder.novelDownStatus.setVisibility(View.VISIBLE);
        holder.novelDownStatus.setImageResource(android.R.drawable.stat_sys_download_done);
      } else if (novel.getDownStatus().equals(CommonUtil.DOWN_STATUS.DOWNING)) {
        holder.novelDownStatus.setVisibility(View.VISIBLE);
        holder.novelDownStatus.setImageResource(R.drawable.ic_downloading);
      } else {
        holder.novelDownStatus.setVisibility(View.INVISIBLE);
      }
//      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//        StateListDrawable stateListDrawable = new StateListDrawable();
//        stateListDrawable.addState(new int[]{android.R.attr.state_activated}, new ColorDrawable(colorAccent));
//        stateListDrawable.addState(StateSet.WILD_CARD, null);
//        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(Color.LTGRAY));
//        stateListDrawable.addState(new int[]{android.R.attr.state_focused}, new ColorDrawable(Color.LTGRAY));
//        //noinspection deprecation
//        holder.itemView.setBackgroundDrawable(stateListDrawable);
//      } else {
//        holder.itemView.setBackgroundResource(R.drawable.bg_activated);
//      }
      ItemClickListener listener = new ItemClickListener(position);
      holder.itemView.setOnClickListener(listener);
      holder.itemView.setOnLongClickListener(listener);
    }
  }

  @Override
  public int getItemCount() {
    int novelSize = mData.size();
    if (hasLoadingMore && novelSize > 0) {
      return novelSize + 1;
    } else {
      return novelSize;
    }
  }

  @Override
  public int getItemViewType(int position) {
    int size = mData.size();
    if (hasLoadingMore && size != 0 && position == size) {
      return VIEW_TYPE_LOAD;
    } else {
      return VIEW_TYPE_NOVEL;
    }
  }

  public void removeItem(int position) {
    if (mData != null && mData.size() > 0 && position >= 0) {
      mData.remove(position);
      notifyItemRemoved(position);
    }
  }

  public void removeItems(ArrayList<Integer> positions) {
    if (positions == null || positions.size() == 0) {
      return;
    }
    Collections.sort(positions, new DescIntComparator());
    int minPos = positions.get(0);
    for (int pos : positions) {
      if (pos < minPos) {
        minPos = pos;
      }
      removeItem(pos);
    }
    notifyItemRangeChanged(minPos, mData.size() - minPos);
  }

  public class NovelRecordViewHolder extends RecyclerView.ViewHolder {
    private ImageView novelCover;
    private TextView novelName;
    private TextView novelProgress;
    private ImageView novelDownStatus;

    public NovelRecordViewHolder(View itemView) {
      super(itemView);
      this.novelCover = (ImageView) itemView.findViewById(R.id.novel_img);
      this.novelName = (TextView) itemView.findViewById(R.id.novel_name);
      this.novelProgress = (TextView) itemView.findViewById(R.id.novel_progress);
      this.novelDownStatus = (ImageView) itemView.findViewById(R.id.novel_down_status);
    }
  }

  public interface NovelRecordItemClickListener {
    void onItemClick(View v, int position, NovelReadRecord record);

    boolean onItemLongClick(View v, int position, NovelReadRecord record);
  }

  private class ItemClickListener implements View.OnClickListener, View.OnLongClickListener {
    private int pos;

    public ItemClickListener(int pos) {
      this.pos = pos;
    }

    @Override
    public void onClick(View v) {
      if (mItemClickListener != null) {
        mItemClickListener.onItemClick(v, pos, mData.get(pos));
      }
    }

    @Override
    public boolean onLongClick(View v) {
      if (mItemClickListener != null) {
        return mItemClickListener.onItemLongClick(v, pos, mData.get(pos));
      }
      return false;
    }
  }
}
